package com.cxs.distributedfiledemo.slice;

import com.cxs.distributedfiledemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.app.Environment;

import java.io.*;

public class MainAbilitySlice extends AbilitySlice {

    File distDir;
    Context context;
    Button btnCreate, btnRead;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initView();
        initEvent();
    }
    /*
        获取组件
     */
    void initView() {
        btnCreate = (Button)findComponentById(ResourceTable.Id_create_file);
        btnRead = (Button)findComponentById(ResourceTable.Id_read_file);
    }

    /*
        初始化按钮事件
     */
    void initEvent() {
        context = this.getContext();

        distDir = context.getDistributedDir();
        String fp1 = distDir + File.separator + "hello.txt";

        String externalCacheDir = context.getExternalCacheDir().getAbsolutePath();
        String fp2 = externalCacheDir + File.separator + "hello.txt";

        String absolutePath = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
        String fp3 = absolutePath + File.separator + "hello.txt";

        btnCreate.setClickedListener(c -> {
            // 创建分布式文件
            // writeFile(fp1);
            // writeFile(fp2);
            writeFile(fp1);
        });
        btnRead.setClickedListener(c -> {
            //读取分布式文件
            // readFile(fp1);
            // readFile(fp2);
            readFile(fp1);
        });
    }

    private void writeFile(String filePath){
        try(OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");){
            osw.write("Hello 鸿蒙");
            System.out.println("写入分布式文件!");
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readFile(String filePath){
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf-8");){
            char[] chars = new char[1024];
            int read = isr.read(chars);
            System.out.println(new String(chars, 0, read));
        }catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
